package com.cyy.partner.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyy.partner.common.Result;
import com.cyy.partner.pojo.Activity;
import com.cyy.partner.pojo.Records;
import com.cyy.partner.pojo.User;
import com.cyy.partner.service.ActivityService;
import com.cyy.partner.service.RecordsService;
import com.cyy.partner.service.UserService;
import com.cyy.partner.utils.JwtUtil;
import com.cyy.partner.utils.Md5Util;
import com.cyy.partner.utils.ThreadLocalUtil;
import com.cyy.partner.utils.ValidatorUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: cyy
 * @Date: 2024/4/26
 */
@Api(tags = "用户管理相关接口")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private RecordsService recordsService;

    @Value("${KEY}")
    private String KEY;

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @ApiOperation("登录用户接口")
    @PostMapping("/login")
    public Result<String> login(String username, String password, Integer isAdmin) {
        //去空格，防止@ptr.com
        username = username.trim();
        //加密
        String pwd = Md5Util.getMD5String(password);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            return Result.error("该用户不存在");
        } else {
            if (!user.getPassword().equals(pwd)) {
                return Result.error("用户密码不对");
            } else {
                if (user.getIsAdmin() != isAdmin) {
                    return Result.error("该用户身份不对哦");
                } else {
                    HashMap<String, Object> claims = new HashMap<>();
                    claims.put("id", user.getId());
                    claims.put("username", user.getUsername());
                    String token = JwtUtil.getToken(claims);
                    return Result.success(token);
                }
            }
        }
    }

    //检查管理员的密钥是否正确
    @ApiOperation("检查管理员的密钥是否正确接口")
    @GetMapping("/register/checkAdmin")
    public Result<String> checkAdmin(String value){
        value = value.trim(); // 去空格
        if(value.equals(KEY)){
            return Result.success("验证成功");
        }else{
            return Result.error("密钥错误");
        }
    }

    /**
     * 用户注册功能
     *
     * @param username
     * @param password
     * @param isAdmin
     * @return
     */
    @ApiOperation("注册用户接口")
    @PostMapping("/register")
    public Result<User> register(String username, String password, Integer isAdmin) {
        username = username.trim();//去空格
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            String pwd = Md5Util.getMD5String(password);
            User user1 = new User(username, pwd, isAdmin);
            //名字存在@字符，邮箱修改
            int idx = username.indexOf('@');
            int len = username.length();
            if(idx != -1 && idx != 0 && idx != len-1){
                user1.setEmail(username);
            }else{
                if(idx == 0)username = username.substring(1);
                if(idx == len-1)username = username.substring(0, len-1);
                user1.setEmail(username + "@ptr.com");
            }
            if(!(password.length() >= 5 && password.length() <= 16)){
                return Result.error("密码长度必须要在5~16位");
            }
            userService.save(user1);
            return Result.success(user1);
        } else {
            return Result.error("该用户已存在");
        }
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @ApiOperation("根据id获取用户信息接口")
    @GetMapping("/userInfo")
    public Result<User> getUserInfo(@ApiParam("用户id") @RequestParam Long id) {
        if (id == -1) {//登录账号的id
            HashMap<String, Object> map = ThreadLocalUtil.get();
            id = (Long) map.get("id");
        }
        User user = userService.getById(id);
        if (user == null) {
            return Result.error("用户不存在哦");
        }
        return Result.success(user);
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @return
     */
    @PutMapping("/update")
    @ApiOperation("更新用户信息接口")
    public Result<String> update(@RequestBody User user) {
//        System.out.println(user);
        if(user.getNickname()==null || user.getAge()==null || user.getEmail()==null){
            return Result.error("请完善您的信息！！！");
        }
        if(!(user.getAge() > 0 && user.getAge() < 150)){
            return Result.error("用户年龄范围出错");
        }
        if(!ValidatorUtil.isEmailNumberValid(user.getEmail())){
            return Result.error("邮箱格式错误");
        }
        if(user.getPhone()!=null && !ValidatorUtil.isPhoneNumberValid(user.getPhone())){
            return Result.error("手机号码格式错误哦");
        }
        user.setIsAdmin(user.getIsAdmin());
        user.setState(user.getState());
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        userService.update(user, updateWrapper.eq(User::getUsername, user.getUsername()));
        return Result.success("用户信息更新成功");
    }

    /**
     * 重置密码
     *
     * @param params
     * @return
     */
    @ApiOperation("重置密码接口")
    @PatchMapping("/resetPassword")
    public Result<String> resetPassword(@RequestBody Map<String, String> params) {
        String newPassword = params.get("newPassword");
        String oldPassword = params.get("oldPassword");
        if(!(newPassword.length() >= 5 && newPassword.length() <= 16)){
            return Result.error("密码长度必须要在5~16位");
        }
        HashMap<String, Object> claims = ThreadLocalUtil.get();
        Long id = (Long) claims.get("id");
        User user = userService.getById(id);
        String md5String = Md5Util.getMD5String(oldPassword);
        if (md5String.equals(user.getPassword())) {
            userService.resetPassword(newPassword);
            return Result.success("重置密码成功");
        } else {
            return Result.error("原密码错误");
        }
    }

    @ApiOperation("重置头像接口")
    @PatchMapping("/updateAvatar")
    public Result<String> resetAvatar(String avatarUrl){
        if(avatarUrl==null){
            return Result.error("请重新选择头像");
        }
//        System.out.println("重置头像函数：" + avatarUrl);
        HashMap<String, Object> map = ThreadLocalUtil.get();
        Long id = (Long) map.get("id");
        User user = userService.getById(id);
        user.setPhoto(avatarUrl);
        userService.updateById(user);
        return Result.success("头像更新成功");
    }

    /**
     * 注销用户
     *
     * @param password
     * @param email
     * @return
     */
    @DeleteMapping
    @ApiOperation("注销用户接口")
    public Result<String> delete(@RequestParam("password") String password, @RequestParam("email") String email) {
        HashMap<String, Object> map = ThreadLocalUtil.get();
        Long id = (Long) map.get("id");
        User user = userService.getById(id);
        if (!Md5Util.getMD5String(password).equals(user.getPassword())) {
            return Result.error("密码错误哦");
        } else if (!user.getEmail().equals(email)) {
            return Result.error("邮箱错误哦");
        }
        //活动记录删除
        LambdaQueryWrapper<Records> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Records::getUserId, id);
        recordsService.remove(queryWrapper);
        LambdaQueryWrapper<Activity> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Activity::getUserId, id);
        activityService.remove(queryWrapper1);

        //令牌移除
        ThreadLocalUtil.remove();
        userService.removeById(id);
        return Result.success("该账号成功注销");
    }

    /**
     * 根据id删除用户
     *
     * @param id
     * @return
     */
    @ApiOperation("删除用户接口")
    @DeleteMapping("/deleteById")
    public Result<String> deleteById(@ApiParam("用户id") Long id) {
//        System.out.println(id);
        User user = userService.getById(id);
        if (user == null) {
            return Result.error("该用户不存在");
        }

        //活动记录删除
        LambdaQueryWrapper<Records> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Records::getUserId, id);
        recordsService.remove(queryWrapper);
        LambdaQueryWrapper<Activity> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Activity::getUserId, id);
        activityService.remove(queryWrapper1);

        userService.removeById(id);
        return Result.success("删除用户成功");
    }

    /**
     * 用户列表
     *
     * @return
     */
    @ApiOperation("所有用户列表接口")
    @GetMapping("/list")
    public Result<List<User>> useList() {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(User::getUpdateTime);
        List<User> list = userService.list();
        return Result.success(list);
    }

    /**
     * 根据分页显示用户列表
     *
     * @param pageNum
     * @param pageSize
     * @param username
     * @return
     */
    @ApiOperation("分页查询用户列表接口")
    @GetMapping("/page")
    public Result<Page> list(int pageNum,
                             int pageSize,
                             @RequestParam(required = false) String username) {
        //分页构造器
        Page<User> pageInfo = new Page<>(pageNum, pageSize);
        //条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(username!=null, User::getUsername, username);
        //按更新时间排序
        queryWrapper.orderByDesc(User::getUpdateTime);
        userService.page(pageInfo, queryWrapper);
        return Result.success(pageInfo);
    }
}
